package com.hefan.common.util;

import org.apache.commons.lang.StringUtils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

/**
 * @author: ninglijun
 * @date: 16/1/16
 * @time: 下午2:05
 * @description:
 */
public class StaticFileUtils {

    /**
     * @param shortUrl 业务中保存的文件路径
     * @return 根据文件路径优化选择cdn域名, 合并后返回
     */
    public static String generateUrlUseCND(String shortUrl) {
        if (StringUtils.isBlank(shortUrl)) {
            return "";
        }
        String[] domains = DynamicProperties.getStringArr("image.url");
        if (domains == null || domains.length == 0) {
            throw new RuntimeException("请在配置文件(resource.properties)中指定使用的cdn域名");
        }
        int hashcode = shortUrl.hashCode();
        return domains[Math.abs(hashcode % domains.length)] + shortUrl;
    }

    public static void createrFile(String fileName, String contentJson) throws Exception {
        String domains = DynamicProperties.getString("static.location");
        if (domains == null || domains.length() == 0) {
            throw new RuntimeException("请在配置文件(resource.properties)中指定");
        }
        FileOutputStream out = new FileOutputStream(domains+fileName);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(contentJson);
        writer.close();
    }
}
